package com.ibeetl.admin.aod;

import com.ibeetl.admin.aod.entity.DieImportTask;
import com.ibeetl.admin.aod.util.DateUtils;
import com.ibeetl.admin.aod.util.ThreadPoolFactory;
import com.ibeetl.admin.aod.util.ToolUtil;
import com.ibeetl.admin.aod.web.dto.AodIndustryDataDto;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicLong;

public class TestInsert {

    static AtomicLong atomicLong = new AtomicLong(1L);

//    public static void main(String[] args) throws Exception {

//        buildResultTestFile();

//    }

    public static void buildResultTestFile() throws Exception {

        String fileEncoding = "gbk";
        String resultFileHeader = "账号,手机号码,时间,内容,地区,供应商,回复,标签,等级,归属地ID";

        BufferedWriter delivrdWriter = null;
        try {
            delivrdWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d://" + DieImportTask.DELIVRD_RESULT_FILE_NAME, false), fileEncoding));
            delivrdWriter.write(resultFileHeader + "\r\n");

            for (int i=0;i<5000040;i++) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("ouyi,")
                        .append("15366093051,")
                        .append("2017-05-29 03:18:52,")
                        .append("亲爱的ding yan：您【美联快递】,");
                stringBuilder.append(",,");
                stringBuilder.append(",")
                        .append("美联快递,")
                        .append("3,")
                        .append("157317,");
                delivrdWriter.write(stringBuilder.toString() + "\r\n");
            }

        } catch (Exception e) {
            throw e;
        } finally {
            if (null != delivrdWriter) {
                delivrdWriter.flush();
                delivrdWriter.close();
            }
        }
    }

    public static void insertData() throws Exception {
        // 开始时间
        System.out.println("开始时间" + new Date());
        Long startTime = (new Date()).getTime();

        ExecutorService threadPool = ThreadPoolFactory.getThreadPool("insert", 10);

        List<FutureTask> futureTasks = new ArrayList<>();
        for (int i=0;i<1;i++) {
            FutureTask<Integer> futureTask = new FutureTask<>(new InsertTASK());
            futureTasks.add(futureTask);
            threadPool.submit(futureTask);
        }

        for (FutureTask futureTask : futureTasks) {
            futureTask.get();
        }


        Long endTime = System.currentTimeMillis();
        System.out.println("共计OK,用时：" + (endTime - startTime));
        threadPool.shutdown();
    }

    static class InsertTASK implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            String url = "jdbc:mysql://127.0.0.1:3306/aod?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false";
            String user = "root";
            String password = "CAO1992bing...";

            // 开始时间
            Long startTime = (new Date()).getTime();

//            String prefix = "insert into aod_industry_data_1(industry_id,account,phone_number,send_time,send_content,status,reply_content,reply_time,number_attribution,label,level,add_time) values ";
            String prefix = "insert into aod_black_list_1(phone_number) values ";

            Connection conn = null;
            PreparedStatement pstm =null;
            ResultSet rt = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(url, user, password);
                conn.setAutoCommit(false);
                StringBuffer suffix = new StringBuffer();
                pstm = conn.prepareStatement("");

                // 外层循环，总提交事务次数
                for (int i = 1; i <= 20; i++) {
                    suffix = new StringBuffer();
                    // 第j次提交步长
                    for (int j = 1; j <= 500000; j++) {
                        // 构建SQL后缀
//                        suffix.append("('999999999','yingzi1066','13886132882','2018-04-12 00:55:05','你的快递将下午2点（代签收）','','',null,88612,'海豚国际儿童',3,'2018-04-12 00:55:05'),");
                        suffix.append("('s" + atomicLong.getAndIncrement() + "'),");
                    }
                    // 构建完整SQL
                    String sql = prefix + suffix.substring(0, suffix.length() - 1);
                    // 添加执行SQL
                    pstm.addBatch(sql);
                    // 清空上一次添加的数据
                    suffix = new StringBuffer();
                    System.out.println("拼装SQL的时间" + new Date());
                }
                pstm.executeBatch();
                // 提交事务
                conn.commit();
                Long endTime = System.currentTimeMillis();
                System.out.println("OK,用时：" + (endTime - startTime));
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }finally{
                if(pstm!=null){
                    try {
                        pstm.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
                if(conn!=null){
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            return 1;
        }
    }

}
